package com.voole.wideget;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Rect;
import android.util.AttributeSet;

import com.android.volley.toolbox.NetworkImageView;
import com.astuetz.viewpager.extensions.sample.R;
import com.facebook.rebound.BaseSpringSystem;
import com.facebook.rebound.SimpleSpringListener;
import com.facebook.rebound.Spring;
import com.facebook.rebound.SpringSystem;
import com.facebook.rebound.SpringUtil;

public class VImageView extends NetworkImageView {

	private Spring mScaleSpring;
	private final BaseSpringSystem mSpringSystem = SpringSystem.create();
	private final ExampleSpringListener mSpringListener = new ExampleSpringListener();

	public VImageView(Context context) {
		super(context);
		vInit();
	}

	public VImageView(Context context, AttributeSet attrs) {
		super(context, attrs);
		vInit();
	}

	public VImageView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		vInit();
	}

	private void vInit() {
		setFocusable(Boolean.TRUE);
		mScaleSpring = mSpringSystem.createSpring();
	}

	@Override
	protected void onFocusChanged(boolean focused, int direction,
			Rect previouslyFocusedRect) {
		super.onFocusChanged(focused, direction, previouslyFocusedRect);
		if (focused) {
			mScaleSpring.setEndValue(1);
			getParent().bringChildToFront(this);
			setBackgroundResource(R.drawable.btn_query_selected);
		} else {
			mScaleSpring.setEndValue(0);
			setBackgroundResource(0);
			
		}
	}

	@SuppressLint("NewApi")
	private void onScale(float x, float y) {
		setScaleX(x);
		setScaleY(y);
	}
	
	@Override
	protected void onDetachedFromWindow() {
		mScaleSpring.removeListener(mSpringListener);
		super.onDetachedFromWindow();
	}
	
	@Override
	protected void onAttachedToWindow() {
		mScaleSpring.addListener(mSpringListener);
		super.onAttachedToWindow();
	}

	private class ExampleSpringListener extends SimpleSpringListener {
		@Override
		public void onSpringUpdate(Spring spring) {
			float mappedValue = (float) SpringUtil.mapValueFromRangeToRange(
					spring.getCurrentValue(), 0, 1, 1, 1.5);onScale(mappedValue, mappedValue);
		}
	}
}
